<?php

namespace common\observer;

use think\Exception;
use support\ErrorCode;
use support\SingletonTrait;
use common\model\TaskModel;
use common\service\CommonService;
use common\service\OptionsService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 动捕任务实体Entity同步动捕师到动捕任务task
 */
class SequenceMotionCaptorSyncToMotionTask implements SplObserver
{
    use SingletonTrait;

    /**
     *
     * @param SplSubject $subject
     * @return void
     * @throws Exception
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['sequence_motion_captor'])) {
            return;
        }
        $motionSequenceCaptor = $updateData['sequence_motion_captor'] ?? '';
        $motionSequenceCaptor = array_filter(explode(',', $motionSequenceCaptor));
        if (empty($motionSequenceCaptor)) {
            return;
        }
        $motionSequenceCaptor = array_shift($motionSequenceCaptor);

        $entity = $subject->getSubjectData();
        if ($entity['module_id'] != module_by_code('sequence')['id']) {
            return;
        }

        $motionTaskStepCode = OptionsService::getInstance()->getOptionsConfigItemData('task_config', 'motion_task_step_code');
        if (empty($motionTaskStepCode)) {
            throw new Exception('missing motion track step code config', ErrorCode::MISSING_CONFIG);
        }
        // 查询序列的第一个任务为动捕任务
        $motionTask = model(TaskModel::class)->where(['entity_id' => $subject->getSplPrimaryId(), 'step_type' => 'step', 'code' => $motionTaskStepCode])->find();
        if (empty($motionTask)) {
            return;
        }
        $taskCommonService = CommonService::instance('task');
        $updateTaskData = [
            'id' => $motionTask['id'],
            'executor' => $motionSequenceCaptor,
            'executor_tenant_id' => $motionTask['tenant_id'],
            'is_assignee' => $motionSequenceCaptor > 0 ? 'yes' : 'no',
            'assignee' => request()->getUserId(),
        ];
        $taskCommonService->update($updateTaskData, 'task', false);
    }
}
